import React, { useState, useEffect } from 'react';
import { getReservations, cancelReservation } from '../services/api';

const Reservations = () => {
  const [reservations, setReservations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState('all');
  const [isInitialLoad, setIsInitialLoad] = useState(true);

  const fetchReservations = async (status = null, showLoading = false) => {
    try {
      if (showLoading) {
        setLoading(true);
      }
      const response = await getReservations(status);
      setReservations(response.data);
      setError(null);
    } catch (err) {
      console.error('获取预约信息失败:', err);
      if (showLoading) {
        setError('获取预约信息失败，请稍后重试');
      }
    } finally {
      if (showLoading) {
        setLoading(false);
        setIsInitialLoad(false);
      }
    }
  };

  useEffect(() => {
    // 首次加载显示loading状态
    fetchReservations(activeTab === 'all' ? null : activeTab, isInitialLoad);
    
    // 添加1秒轮询，不触发loading状态
    const intervalId = setInterval(() => {
      fetchReservations(activeTab === 'all' ? null : activeTab, false);
    }, 1000);
    
    return () => clearInterval(intervalId);
  }, [activeTab, isInitialLoad]);

  const handleTabChange = (tab) => {
    setActiveTab(tab);
    // 切换标签页时立即获取数据，但不显示加载状态
    fetchReservations(tab === 'all' ? null : tab, false);
  };

  const handleCancelReservation = async (id) => {
    if (window.confirm('确定要取消此预约吗？')) {
      try {
        await cancelReservation(id);
        // 刷新预约列表
        fetchReservations(activeTab === 'all' ? null : activeTab, false);
      } catch (err) {
        console.error('取消预约失败:', err);
        alert('取消预约失败，请稍后重试');
      }
    }
  };

  const getStatusBadge = (status) => {
    switch (status) {
      case 'waiting_entry':
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">待入场</span>;
      case 'entered':
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">已入场</span>;
      case 'exited':
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-indigo-100 text-indigo-800">已出场</span>;
      case 'waiting_payment':
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-orange-100 text-orange-800">待支付</span>;
      case 'completed':
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">已完单</span>;
      case 'cancelled':
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800">已取消</span>;
      // 兼容旧状态
      case 'pending':
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800">待入场</span>;
      case 'active':
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">已入场</span>;
      default:
        return <span className="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">未知</span>;
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
          <p>{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-800">预约管理</h1>
      </div>
      
      <div className="bg-white rounded-lg shadow-md">
        <div className="border-b border-gray-200">
          <nav className="flex -mb-px overflow-x-auto">
            <button
              className={`px-4 py-3 border-b-2 text-sm font-medium whitespace-nowrap ${
                activeTab === 'all'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
              onClick={() => handleTabChange('all')}
            >
              全部
            </button>
            <button
              className={`px-4 py-3 border-b-2 text-sm font-medium whitespace-nowrap ${
                activeTab === 'waiting_entry'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
              onClick={() => handleTabChange('waiting_entry')}
            >
              待入场
            </button>
            <button
              className={`px-4 py-3 border-b-2 text-sm font-medium whitespace-nowrap ${
                activeTab === 'entered'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
              onClick={() => handleTabChange('entered')}
            >
              已入场
            </button>
            <button
              className={`px-4 py-3 border-b-2 text-sm font-medium whitespace-nowrap ${
                activeTab === 'waiting_payment'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
              onClick={() => handleTabChange('waiting_payment')}
            >
              待支付
            </button>
            <button
              className={`px-4 py-3 border-b-2 text-sm font-medium whitespace-nowrap ${
                activeTab === 'completed'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
              onClick={() => handleTabChange('completed')}
            >
              已完单
            </button>
            <button
              className={`px-4 py-3 border-b-2 text-sm font-medium whitespace-nowrap ${
                activeTab === 'cancelled'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
              onClick={() => handleTabChange('cancelled')}
            >
              已取消
            </button>
          </nav>
        </div>
        
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  ID
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  车牌号
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  车位号
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  预约时间
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  结束时间
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {reservations.map((reservation) => (
                <tr key={reservation.id}>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {reservation.id}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    {reservation.plate_number}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {reservation.spot_number}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {new Date(reservation.start_time).toLocaleString()}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {reservation.end_time ? new Date(reservation.end_time).toLocaleString() : '-'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {getStatusBadge(reservation.status)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {reservation.status === 'waiting_entry' && (
                      <button
                        className="text-red-600 hover:text-red-900"
                        onClick={() => handleCancelReservation(reservation.id)}
                      >
                        取消
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          
          {reservations.length === 0 && (
            <p className="text-gray-500 text-center py-8">暂无预约信息</p>
          )}
        </div>
      </div>
    </div>
  );
};

export default Reservations; 